package de.westranger.forex.trading.genetic.allel.selection;

import java.util.Arrays;
import java.util.Random;

import de.westranger.forex.trading.genetic.allel.chromosom.Chromosom;
import de.westranger.forex.trading.genetic.allel.operator.Util;

public final class Selection {
	private final Random rnd;

	public Selection() {
		this.rnd = new Random();

		for (int i = 0; i < 100000; i++) {
			rnd.nextDouble();
		}
	}
	
	public Chromosom[] selectStockasticUniversalSampling(final Chromosom[] population) {
		final Chromosom[] newPopulation = new Chromosom[population.length];
		final double avg = 1.0/(double)population.length;
		double target = this.rnd.nextDouble() *avg;
	
		Util.normalize(population);
		Arrays.sort(population, new ChromosomComparator());

		int pos = 0;
		for (int j = 0; j < population.length; j++) {
			double tmpSum = 0.0;
			for (int i = 0; i < population.length; i++) {
				if(inbetween(target,tmpSum,tmpSum+population[i].getFitness())){
					newPopulation[pos++] = population[i];
					target += avg;	
					break;
				}

				tmpSum += population[i].getFitness();
			}			
		}
		if(pos == 0){
			throw new IllegalStateException("nothing was selected during sampling");
		}else{
			return newPopulation;			
		}
	}

	private boolean inbetween(final double value, final double intervalStart, final double intervalEnd){
		boolean result = false;
		if(value >= intervalStart && value <= intervalEnd){
			result = true;
		}
		return result;
	}
	
}
